package com.example.javafx.javafx.controller;

import com.example.javafx.entity.LoginRequest;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.fxml.FXML;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

public class LoginController {
    @FXML
    private TextField usernameField;
    @FXML private PasswordField passwordField;
    @FXML private Label errorLabel;

    private RestTemplate restTemplate = new RestTemplate();

    @FXML
    private void handleLogin() {
        String username = usernameField.getText();
        String password = passwordField.getText();

        // 调用后端登录API
        LoginRequest request = new LoginRequest(username, password);
        ResponseEntity<?> response = restTemplate.postForEntity(
                "http://localhost:8080/api/users/login",
                request,
                Void.class
        );

        if (response.getStatusCode() == HttpStatus.OK) {
            // 登录成功，跳转主页面
            loadMainView();
        } else {
            errorLabel.setText("用户名或密码错误！");
        }
    }

    private void loadMainView() {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("/com/example/javafx/main-view.fxml"));
            Stage stage = (Stage) usernameField.getScene().getWindow();
            stage.setScene(new Scene(root, 800, 600));
            stage.setTitle("用户管理系统");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}